require(['./config'], () => {
    require(['template', 'header','footer'], (template) => {
      class Shoppingcart {
        constructor () {
          this.render()
          this.calcTotalMoney()
          this.checksChange()
          this.setAllCheckStatus()
        }
        render () {
          const cart = localStorage.getItem('cart')
          if (cart) {
            this.cart = JSON.parse(cart)
            $('#shop_tbody').html(template('cartTemplate', { cart: this.cart }))
          } else {
            // 购物车为空
            $('#shopping_car').hide()
            $('#cart-empty').show()
          }
        }
        checksChange () {
          const _this = this
          $('.checks').on('change', function () {
            // 把当前数据的check属性修改为这个checkbox的checked状态
            const id = Number($(this).parents('tr').attr('data-id'))
            _this.cart = _this.cart.map(shop => {
              if (shop.id === id) shop.check = $(this).prop('checked')
              return shop
            })
            // 页面显示、this.cart以及localStorage三者要统一
            localStorage.setItem('cart', JSON.stringify(_this.cart))
            // 重新计算总价
            _this.calcTotalMoney()
            // 重新设置全选状态
            _this.setAllCheckStatus()
          })
        }
        setAllCheckStatus () {
          // 判断cart是否全部check为true
          const isAllCheck = this.cart.every(shop => shop.check)
          $('#all-check').prop('checked', isAllCheck)
        }
        calcTotalMoney () {
          // 用数据来算，this.cart
          const money = this.cart.reduce((total, shop) => {
            if (shop.check) total += shop.count * shop.price
            return total
          }, 0)
          $('#Paymoney').html(money.toFixed(2))
        }
      }
      new Shoppingcart()
    })
  })